package com.heima.app.gateway.filter;

import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @author Jt
 * @date 2021/4/12 15:42
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {

    //    存储放行路径 (存放所有放行路径)
    List<String> list = Arrays.asList(
            "login",
            "v2/api-docs"
    );

    /**
     * 过滤方法
     *
     * @param exchange 封装了请求和响应对象
     * @param chain    链对象
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        1.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
//        2.查询路径是否需要拦截
        String path = request.getURI().getPath();
//        进行判断
        for (String s : list) {
            if (path.contains(s)) {
//                说明包含,进行放行
                return chain.filter(exchange);
            }
        }
//        3.获取请求头中的token信息
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
//        4.如为空.终止请求并响应未认证
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 响应认证(401)
            return response.setComplete(); // 终止请求
        }
//        5.验证token是否有效
        try {
//            解析token获取载荷信息
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claims);
//            进行判断 小于1说明有效
            if (i < 1) {
//        6.如有效,获取token存储的用户id,将用户id存储到请求中,然后放行
                Integer id = claims.get("id", Integer.class);
//                改变请求的状态
                ServerHttpRequest request1 = request.mutate().header("userId", String.valueOf(id)).build();
//                改变exchange的状态,并且对请求进行放行,传递下一个过滤器
                return chain.filter(exchange.mutate().request(request1).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("jwt token 解析出现异常 ===> {}",e);
        }
//        7.如无效,终止请求,并响应未认证
        response.setStatusCode(HttpStatus.UNAUTHORIZED); // 响应认证
        return response.setComplete(); // 终止请求
    }

}
